//
//  DWRollScrollView.m
//  scrollView
//
//  Created by 吴建东 on 16/6/13.
//  Copyright © 2016年 DickyWoo. All rights reserved.
//

#import "DWRollScrollView.h"
#import "UIImageView+WebCache.h"

@interface DWRollScrollView ()<UIScrollViewDelegate> {
    
}
@property (nonatomic, strong) UIScrollView *scrollView;//滚动视图
@property (nonatomic, strong) UIImageView  *leftImageView;//左视图
@property (nonatomic, strong) UIImageView  *centerImageView;//中间视图
@property (nonatomic, strong) UIImageView  *rightImageView;//右视图
@property (nonatomic, assign) CGFloat      contentViewWidth;//内容视图宽度
@property (nonatomic, assign) CGFloat      imageWidth;//图片宽度
@property (nonatomic, assign) CGFloat      scrollViewWidth;//图片宽度
@property (nonatomic, assign) NSInteger    currentIndex;//滚动标识
@property (nonatomic, assign) NSInteger    selectIndex;//选中标识


@property (nonatomic, weak) NSTimer *timer;
@end

@implementation DWRollScrollView
#pragma mark - Life Cycle
- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _verticalInterval = 10.0f;
        _cornerRadius = 0.0f;
        _showRedundantWidth = 10.0f;
        _currentIndex = 0;
        _selectIndex = 0;
        _autoScrollTimeInterval = 5.0;
        _autoScroll = YES;
        
        _imageWidth = self.frame.size.width - _verticalInterval*2 - _showRedundantWidth*2;
        _contentViewWidth = _imageWidth + _verticalInterval;
        _scrollViewWidth = self.frame.size.width;
        
        [self initView];
    }
    return self;
}

- (void)willMoveToSuperview:(nullable UIView *)newSuperview {
    if (!newSuperview) {
        [self invalidateTimer];
    }
}

- (void)dealloc {
    [self invalidateTimer];
    _scrollView.delegate = nil;
}

#pragma mark - Action
/**
 *  点击事件处理
 */
- (void)dealCenterImageViewTap {
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(scrollViewDidSelectAtIndex:)]) {
        [self.delegate scrollViewDidSelectAtIndex:_selectIndex];
    }
}

/**
 *  刷新页面
 */
- (void)reloadView {
    if (_scrollView) {
        [self reloadScrollViewData];
    }
}

- (void)automaticScroll {
    if (_imageDataArray.count <= 1) return;
    
    [self currentIndexAdd];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self invalidateTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self fireTimer];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (_imageDataArray.count <= 0) {
        return;
    }
    CGFloat offSet = _scrollView.contentOffset.x;
    
    if (offSet >= _scrollViewWidth*2 - (_verticalInterval+_showRedundantWidth)*2) {
        
        [self currentIndexAdd];
    }
    
    if (offSet <= (_verticalInterval+_showRedundantWidth)*2) {
        
        [self currentIndexMinus];
    }
    
}

- (void)currentIndexAdd {
    [self resetScrollView];

    _currentIndex ++;
    if (_currentIndex == _imageDataArray.count-1) {
        [self setImageForImageView:_leftImageView withImageFile:_imageDataArray[_currentIndex - 1]];
        [self setImageForImageView:_centerImageView withImageFile:_imageDataArray[_currentIndex]];
        [self setImageForImageView:_rightImageView withImageFile:_imageDataArray.firstObject];
        
        _selectIndex = _currentIndex;
        _currentIndex = -1;
        
    }else if (_currentIndex == _imageDataArray.count) {
        [self setImageForImageView:_leftImageView withImageFile:_imageDataArray.lastObject];
        [self setImageForImageView:_centerImageView withImageFile:_imageDataArray.firstObject];
        [self setImageForImageView:_rightImageView withImageFile:_imageDataArray[1]];
        
        _selectIndex = 0;
        _currentIndex = 0;
        
    }else if (_currentIndex == 0) {
        [self setImageForImageView:_leftImageView withImageFile:_imageDataArray.lastObject];
        [self setImageForImageView:_centerImageView withImageFile:_imageDataArray[_currentIndex]];
        [self setImageForImageView:_rightImageView withImageFile:_imageDataArray[_currentIndex + 1]];
        
        _selectIndex = _currentIndex;
        
    }else {
        [self setImageForImageView:_leftImageView withImageFile:_imageDataArray[_currentIndex - 1]];
        [self setImageForImageView:_centerImageView withImageFile:_imageDataArray[_currentIndex]];
        [self setImageForImageView:_rightImageView withImageFile:_imageDataArray[_currentIndex + 1]];
        
        _selectIndex = _currentIndex;
    }
}

- (void)currentIndexMinus {
    [self resetScrollView];

    _currentIndex --;
    if (_currentIndex == -2) {
        _currentIndex = _imageDataArray.count - 2;
        
        [self setImageForImageView:_leftImageView withImageFile:_imageDataArray[_imageDataArray.count - 1]];
        [self setImageForImageView:_centerImageView withImageFile:_imageDataArray[_currentIndex]];
        [self setImageForImageView:_rightImageView withImageFile:_imageDataArray.lastObject];
        
    }else if (_currentIndex == -1) {
        _currentIndex = _imageDataArray.count - 1;
        
        [self setImageForImageView:_leftImageView withImageFile:_imageDataArray[_currentIndex - 1]];
        [self setImageForImageView:_centerImageView withImageFile:_imageDataArray[_currentIndex]];
        [self setImageForImageView:_rightImageView withImageFile:_imageDataArray.firstObject];
        
    }else if (_currentIndex == 0) {
        [self setImageForImageView:_leftImageView withImageFile:_imageDataArray.lastObject];
        [self setImageForImageView:_centerImageView withImageFile:_imageDataArray[_currentIndex]];
        [self setImageForImageView:_rightImageView withImageFile:_imageDataArray[_currentIndex + 1]];
        
    }else {
        [self setImageForImageView:_leftImageView withImageFile:_imageDataArray[_currentIndex - 1]];
        [self setImageForImageView:_centerImageView withImageFile:_imageDataArray[_currentIndex]];
        [self setImageForImageView:_rightImageView withImageFile:_imageDataArray[_currentIndex + 1]];
        
    }
    _selectIndex = _currentIndex;
}

#pragma mark - property
- (void)setAutoScroll:(BOOL)autoScroll {
    _autoScroll = autoScroll;
    
    [self invalidateTimer];
    [self fireTimer];
}

/**
 *  重置数据源
 */
- (void)setImageDataArray:(NSMutableArray *)imageDataArray {
    _imageDataArray = imageDataArray;
    
    [self reloadScrollViewData];
}

/**
 *  重置圆角属性
 */
- (void)setCornerRadius:(CGFloat)cornerRadius {
    _cornerRadius = cornerRadius;
    _leftImageView.layer.cornerRadius = _cornerRadius;
    _centerImageView.layer.cornerRadius = _cornerRadius;
    _rightImageView.layer.cornerRadius = _cornerRadius;
}

/**
 *  重置左右显示视图的宽度
 */
- (void)setShowRedundantWidth:(CGFloat)showRedundantWidth {
    _showRedundantWidth = showRedundantWidth<=self.frame.size.width/10?showRedundantWidth : self.frame.size.width/10;

    [self reloadFrame];
}

/**
 *  重置图片间的间距
 */
- (void)setVerticalInterval:(CGFloat)verticalInterval {
    _verticalInterval = verticalInterval<=self.frame.size.width/10?verticalInterval:self.frame.size.width/10;
    
    [self reloadFrame];
}

#pragma mark - SetData
- (void)reloadScrollViewData {
    _currentIndex = 0;
    _selectIndex = 0;
    [self resetScrollView];
    
    if (_imageDataArray.count <= 0) {
        _leftImageView.hidden   = YES;
        _centerImageView.hidden = YES;
        _rightImageView.hidden  = YES;
        
        [self setScrollViewEnable:NO];
        
    }else if (_imageDataArray.count == 1) {
        _leftImageView.hidden   = YES;
        _centerImageView.hidden = NO;
        _rightImageView.hidden  = YES;
        
        [self setScrollViewEnable:NO];
        
        [self setImageForImageView:_centerImageView withImageFile:_imageDataArray.firstObject];
        
    }else if (_imageDataArray.count == 2) {
        _leftImageView.hidden   = NO;
        _centerImageView.hidden = NO;
        _rightImageView.hidden  = NO;
        
        [self setScrollViewEnable:YES];
        
        [self setImageForImageView:_leftImageView withImageFile:_imageDataArray.lastObject];
        [self setImageForImageView:_centerImageView withImageFile:_imageDataArray.firstObject];
        [self setImageForImageView:_rightImageView withImageFile:_imageDataArray[1]];
        
    }else {
        _leftImageView.hidden   = NO;
        _centerImageView.hidden = NO;
        _rightImageView.hidden  = NO;
        
        [self setScrollViewEnable:YES];
        
        [self setImageForImageView:_leftImageView withImageFile:_imageDataArray.lastObject];
        [self setImageForImageView:_centerImageView withImageFile:_imageDataArray.firstObject];
        [self setImageForImageView:_rightImageView withImageFile:_imageDataArray[1]];
    }
}

- (void)setScrollViewEnable:(BOOL)enable {
    if (enable) {
        _scrollView.scrollEnabled = YES;
        [self fireTimer];
    }else {
        _scrollView.scrollEnabled = NO;
        [self invalidateTimer];
    }
}

/**
 *  加载图片，自动判断是否是网络图片
 *
 *  @param imageView 需要加载的imageView
 *  @param imageFile 图片路径
 */
- (void)setImageForImageView:(UIImageView *)imageView withImageFile:(AdvertiseGallery *)imageData {
    NSString *imageFile = imageData.image;
    if ([imageFile hasPrefix:@"http"]) {
        [imageView sd_setImageWithURL:[NSURL URLWithString:imageFile]];
    }else {
        [imageView setImage:[UIImage imageNamed:imageFile]];
    }
}

#pragma mark - View
- (void)reloadFrame {
    _imageWidth = self.frame.size.width - _verticalInterval*2 - _showRedundantWidth*2;
    _contentViewWidth = _imageWidth + _verticalInterval;
    
    _leftImageView.frame = CGRectMake(_showRedundantWidth - _imageWidth + _scrollViewWidth, CGRectGetMinY(_scrollView.frame), _imageWidth, CGRectGetHeight(_scrollView.frame));
    _centerImageView.frame = CGRectMake(CGRectGetMaxX(_leftImageView.frame) + _verticalInterval, CGRectGetMinY(_scrollView.frame), _imageWidth, CGRectGetHeight(_scrollView.frame));
    _rightImageView.frame = CGRectMake(CGRectGetMaxX(_centerImageView.frame) + _verticalInterval, CGRectGetMinY(_scrollView.frame), _imageWidth, CGRectGetHeight(_scrollView.frame));
}

- (void)resetScrollView {
    [_scrollView resignFirstResponder];
    [_scrollView setContentOffset:CGPointMake(_scrollViewWidth, 0) animated:NO];
}

- (void)fireTimer {
    if (_autoScroll) {
        [self invalidateTimer];
        
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:_autoScrollTimeInterval target:self selector:@selector(automaticScroll) userInfo:nil repeats:YES];
        _timer = timer;
        [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    }
}

- (void)invalidateTimer {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

- (void)initView {
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    _scrollView.pagingEnabled = YES;
    _scrollView.delegate = self;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.contentSize = CGSizeMake((CGRectGetWidth(_scrollView.frame))*3, 0);
    [self addSubview:_scrollView];
    
    [self resetScrollView];
    
    _leftImageView = [[UIImageView alloc] init];
    [_scrollView addSubview:_leftImageView];
    _leftImageView.clipsToBounds = YES;
    _leftImageView.layer.cornerRadius = _cornerRadius;
    _leftImageView.hidden = YES;
    
    _centerImageView = [[UIImageView alloc] init];
    [_scrollView addSubview:_centerImageView];
    _centerImageView.clipsToBounds = YES;
    _centerImageView.layer.cornerRadius = _cornerRadius;
    _centerImageView.hidden = YES;
    _centerImageView.userInteractionEnabled = YES;
    [_centerImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dealCenterImageViewTap)]];
    
    _rightImageView = [[UIImageView alloc] init];
    [_scrollView addSubview:_rightImageView];
    _rightImageView.clipsToBounds = YES;
    _rightImageView.layer.cornerRadius = _cornerRadius;
    _rightImageView.hidden = YES;
    
    [self reloadFrame];
    [self reloadScrollViewData];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
